package org.spring.aicloud.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.spring.aicloud.DTO.UserDTO;
import org.spring.aicloud.entity.User;
import org.spring.aicloud.service.impl.UserServiceImpl;
import org.spring.aicloud.utils.NameUtil;
import org.spring.aicloud.utils.ResponseEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * @author yexiebao
 * @date 2025/5/6
 */

@RestController
@RequestMapping("/user")
@Tag(name = "用户控制器")
public class UserController {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private UserServiceImpl userService;
    //读取密钥
    @Value("${jwt.secret}")
    private String jwtSecret;
    @Resource
    private PasswordEncoder passwordEncoder;

    /**
     * 登录
     * @param userDTO
     * @return
     */
    @RequestMapping("/login")
    public ResponseEntity login(@Validated UserDTO userDTO, HttpServletRequest request) {

        //验证码在redis的key
        String redisKeyOfCaptcha = NameUtil.getCaptchaName(request);
        //从redis取出验证码
        String redisCaptcha = (String) redisTemplate.opsForValue().get(redisKeyOfCaptcha);

        if (!StringUtils.hasLength(redisCaptcha)) {
            return ResponseEntity.error("验证码已过期");
        }
        //忽略大小写
        if (!redisCaptcha.equalsIgnoreCase(userDTO.getCaptcha())) {
            return ResponseEntity.error("验证码错误");
        }
        //验证登录
        QueryWrapper<User>queryWrapper = new QueryWrapper<>();
        //构造查询条件
        queryWrapper.eq("username",userDTO.getUsername());
        //查询用户
        User user = userService.getOne(queryWrapper);
        //验证用户
        if (user != null && passwordEncoder.matches(userDTO.getPassword(), user.getPassword())) {
            //登陆成功，生成jwt
            HashMap<String, Object> payLoad = new HashMap<>();
            payLoad.put("username",user.getUsername());
            payLoad.put("uid",user.getUid());
            //封装jwt和username
            HashMap<String,String>userInfo = new HashMap<>();
            userInfo.put("username",user.getUsername());
            userInfo.put("jwt",JWTUtil.createToken(payLoad, jwtSecret.getBytes()));
            return ResponseEntity.ok(userInfo);
        }
        return ResponseEntity.error("用户名或密码错误");
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @RequestMapping("/register")
    public ResponseEntity register(@Validated User user){
        //将密码进行加盐处理
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //添加用户
        boolean result = userService.save(user);
        if (!result) {
            return ResponseEntity.error("注册失败");
        }
        return ResponseEntity.ok("注册成功");
    }

    @Operation(summary = "测试接口")
    @PostMapping("/test")
    @Parameters({
            @Parameter(name = "msg",description = "消息内容")
    })
    public String test(String msg){
        return"ok";
    }
}